//
//  FootViewController.m
//  FKGW
//
//  Created by song ce on 2017/2/15.
//  Copyright © 2017年 song ce. All rights reserved.
//

#import "FootViewController.h"
#import "FootCell.h"
#import "LoginViewController.h"
#import "GoodsDetailViewController.h"
@interface FootViewController ()<UITableViewDelegate,UITableViewDataSource>
@property(nonatomic,strong)UITableView *tableV;
@property(nonatomic,strong)NSMutableArray *dataSource;
@property(nonatomic,strong)LoginViewController  *login;
@property(nonatomic,assign)BOOL isFirstLoadData;
@end

@implementation FootViewController
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(self.isFirstLoadData){
        self.isFirstLoadData = NO;
        return;
    }
    if([AppDelegate appDealegate].uid.length&&[AppDelegate appDealegate].isNeedUpdateFooter){
        [AppDelegate appDealegate].isNeedUpdateFooter = NO;
        [self loadData];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.vcName = @"足迹";
    [self initRightBarItem];
    //数据源
    self.dataSource = [NSMutableArray array];
    //表示图
    [self tableViewAndHeaderView];
    if([AppDelegate appDealegate].uid.length){
        self.isFirstLoadData = YES;
        [self loadData];
        return;
    }
    [self addLoginView];
    //登录成功通知
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginSuccess) name:@"loginSuccess" object:nil];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(logOutSuccess) name:@"logOutSuccess" object:nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}

//接受到登录成功的通知后加载数据
-(void)loginSuccess{
    if(self.login!=nil){
        [self.login.navigationController popViewControllerAnimated:NO];
        self.login = nil;
    }
    //加载数据
    [self loadData];
}
-(void)logOutSuccess{
     [self addLoginView];
}
-(void)addLoginView{
    if(![AppDelegate appDealegate].uid.length){
        LoginViewController *login = [[LoginViewController alloc]init];
        self.login = login;
        login.isNotNeedBackBtn = YES;
        [self.navigationController pushViewController:login animated:NO];
    }
}
-(void)loadData{
    //2.59 足迹接口
    NSDictionary *paraDic = @{
                              @"userId":USERID,
                              };
    __weak typeof(self)  weakSelf = self;
    [MBProgressHUD showLoadingGif];
    [Tools AFNetworkingRequestTypePostWithUrl:MYFOOTPRINT paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"足迹接口--%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSArray *data = resultDic[@"data"];
            if([data isKindOfClass:[NSNull class]]){
                [MBProgressHUD dismissHUD];
                return ;
            }
            if(weakSelf.dataSource.count){
                [weakSelf.dataSource removeAllObjects];
            }
            for(NSDictionary *dic  in data){
                FootModel *model = [FootModel modelWithDic:dic];
                [weakSelf.dataSource addObject:model];
            }
            if(!weakSelf.dataSource.count){
                 [MBProgressHUD dismissHUD];
                [weakSelf.view addSubview:weakSelf.noDataIUmageV];
                return;
            }else{
                [weakSelf.noDataIUmageV removeFromSuperview];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                //刷新页面
                [self.tableV reloadData];
                self.tableV.hidden = NO;
                [MBProgressHUD dismissHUD];
            });
        }else{
            [MBProgressHUD dismissHUD];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

- (void)initRightBarItem{
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeCustom];
    rightButton.frame=CGRectMake(0, 0, 50, 40);
    [rightButton setTitle:@"清空" forState:UIControlStateNormal];
    rightButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [rightButton setTitleColor:DEF_COLOR  forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightA_ction) forControlEvents:UIControlEventTouchUpInside];
    self.rightItem = rightButton;
}

-(void)rightA_ction{
   // 2.59 足迹清空
    NSDictionary *paraDic = @{
                              @"userId":USERID,
                              @"pId":@"",//商品标识（可为空字符串）
                              @"isAll":@"true",
                              };
    __weak typeof(self)  weakSelf = self;
    [MBProgressHUD showTipMessageInWindow:@""];
    [Tools AFNetworkingRequestTypePostWithUrl:MYFOOTPRINTCLEAR paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
        DLog(@"足迹清空/删除接口---%@",resultDic);
        if([resultDic[@"flag"] isEqualToString:@"true"]){
            NSDictionary *dataDic = resultDic[@"data"];
            if([dataDic isKindOfClass:[NSNull class]]){
                [MBProgressHUD dismiss];
            }
            if([dataDic[@"status"] isEqualToString:@"true"]){
                [MBProgressHUD dismiss];
                [MBProgressHUD showTipMessageInView:@"已清空足迹"];
                weakSelf.tableV.hidden = YES;
                [weakSelf.dataSource removeAllObjects];
                [weakSelf.view addSubview:weakSelf.noDataIUmageV];
            }else{
                if(dataDic[@"errorString"]){
                    NSString *message = dataDic[@"errorString"];
                    [MBProgressHUD dismiss];
                    if(message.length){
                         [MBProgressHUD showTipMessageInWindow:message];
                    }else{
                        [MBProgressHUD showTipMessageInView:@"已清空足迹"];
                        [weakSelf.view addSubview:weakSelf.noDataIUmageV];
                    }
                }
            }
        }else{
            [MBProgressHUD dismiss];
            if(resultDic[@"errorString"]){
                [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
            }
        }
    }];
}

-(void)tableViewAndHeaderView{
    //表视图
    _tableV = [[UITableView alloc]initWithFrame:CGRectMake(0, kNaviBarHeight, Main_Screen_Width, Main_Screen_Height-kNaviBarHeight-49) style:UITableViewStylePlain];
    _tableV.showsVerticalScrollIndicator = NO;
    _tableV.backgroundColor = DEF_COLOR242;
    _tableV.delegate = self;
    _tableV.dataSource =self;
    [self.view addSubview:_tableV];
     _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
      _tableV.tableFooterView = [[UIView alloc]init];
    _tableV.hidden = YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *ident=@"sessioncell";
    FootCell *cell=[tableView dequeueReusableCellWithIdentifier:ident];
    if(cell==nil){
        cell=[[[NSBundle mainBundle]loadNibNamed:@"FootCell" owner:self options:nil]lastObject];
    }
    FootModel *model = self.dataSource[indexPath.row];
//    __weak typeof (self) weakSelf = self;
    __weak typeof (cell) weakCell = cell;
    cell.mySwipeBlock = ^{
        for(FootCell *tmpCell in tableView.visibleCells){
            // 将其他正在打开的cell关闭
            if (![weakCell isEqual:tmpCell]) {
                [tmpCell closeMenu];
            }
            // 所有cell取消选中状态
            tmpCell.selected = NO;
        }
    };
    //删除回调
    cell.myDeleteBlock =^{
        DLog(@"shanchu");
        // 2.59 删除接口
        NSDictionary *paraDic = @{
                                  @"userId":USERID,
                                  @"pId":model.pId,//商品标识（可为空字符串）
                                  @"isAll":@"false",
                                  };
        [Tools AFNetworkingRequestTypePostWithUrl:MYFOOTPRINTCLEAR paramters:paraDic  afterResultBlock:^(NSDictionary *resultDic) {
            DLog(@"足迹清空/删除接口---%@",resultDic);
            if([resultDic[@"flag"] isEqualToString:@"true"]){
                NSDictionary *dataDic = resultDic[@"data"];
                 if([dataDic isKindOfClass:[NSNull class]]) return ;
                if([dataDic[@"status"] isEqualToString:@"true"]){
                      [MBProgressHUD showTipMessageInWindow:@"删除成功"];
                    //回到主线程刷新UI
                    dispatch_async(dispatch_get_main_queue(), ^{
                        if (self.dataSource.count) {
                            DLog(@"将要删除-- %ld", indexPath.row);

                            [self.dataSource removeObjectAtIndex:indexPath.row];
                            [self.tableV reloadData];
                            if(self.dataSource.count==0){
                                self.tableV.hidden = YES;
                                return ;
                            }
//                            if (indexPath.row == self.dataSource.count) {
//                                // 删除的是最后一个直接刷新
//                                [self.tableV reloadData];
//                            }else{
//                                // 删除其他的cell，带动画
//                                [self.tableV deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                                [self.tableV reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
//                            }
                        }
                    });
                }else{
                    if(dataDic[@"errorString"]){
                        [MBProgressHUD showTipMessageInWindow:dataDic[@"errorString"]];
                    }
                }
            }else{
                if(resultDic[@"errorString"]){
                    [MBProgressHUD showTipMessageInWindow:resultDic[@"errorString"]];
                }
            }
        }];
};
    cell.model = model;
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 112;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    FootModel *model = self.dataSource[indexPath.row];
    GoodsDetailViewController *goodsDetail  = [[GoodsDetailViewController alloc]init];
    goodsDetail.pid = model.pId;
    goodsDetail.goodPic = model.pPic;
    goodsDetail.isNeedMessageItem = YES;
    [self.navigationController pushViewController:goodsDetail animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
